<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-card>
        <div slot="header">
          <span>{{ isEdit ? '修改订单' : '手动补录订单' }}</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回</el-button>
        </div>

        <!-- 基本信息 -->
        <h3>基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="订单号" prop="orderNo">
              <el-input v-model="form.orderNo" placeholder="自动生成，可手动修改" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="平台订单号" prop="platformOrderNo">
              <el-input v-model="form.platformOrderNo" placeholder="请输入平台订单号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="平台类型" prop="platformType">
              <el-select v-model="form.platformType" placeholder="请选择平台类型" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.fiscale_platform_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="订单状态" prop="orderStatus">
              <el-select v-model="form.orderStatus" placeholder="请选择订单状态" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.fiscale_order_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="报关状态" prop="customsStatus">
              <el-select v-model="form.customsStatus" placeholder="请选择报关状态" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.fiscale_customs_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单日期" prop="orderDate">
              <el-date-picker
                v-model="form.orderDate"
                type="datetime"
                placeholder="选择订单日期"
                style="width: 100%"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 客户信息 -->
        <h3 style="margin-top: 30px;">客户信息</h3>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="客户姓名" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请输入客户姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户邮箱" prop="customerEmail">
              <el-input v-model="form.customerEmail" placeholder="请输入客户邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户电话" prop="customerPhone">
              <el-input v-model="form.customerPhone" placeholder="请输入客户电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 订单信息 -->
        <h3 style="margin-top: 30px;">订单信息</h3>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="订单金额" prop="totalAmount">
              <el-input v-model="form.totalAmount" placeholder="请输入订单金额" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货币类型" prop="currency">
              <el-select v-model="form.currency" placeholder="请选择货币类型" style="width: 100%">
                <el-option label="USD" value="USD" />
                <el-option label="CNY" value="CNY" />
                <el-option label="EUR" value="EUR" />
                <el-option label="GBP" value="GBP" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="支付状态" prop="paymentStatus">
              <el-select v-model="form.paymentStatus" placeholder="请选择支付状态" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.fiscale_payment_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-input v-model="form.paymentMethod" placeholder="请输入支付方式" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送方式" prop="shippingMethod">
              <el-input v-model="form.shippingMethod" placeholder="请输入配送方式" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物流跟踪号" prop="trackingNumber">
              <el-input v-model="form.trackingNumber" placeholder="请输入物流跟踪号" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 地址信息 -->
        <h3 style="margin-top: 30px;">地址信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收货地址" prop="shippingAddress">
              <el-input
                v-model="form.shippingAddress"
                type="textarea"
                :rows="4"
                placeholder="请输入收货地址JSON格式或文本"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账单地址" prop="billingAddress">
              <el-input
                v-model="form.billingAddress"
                type="textarea"
                :rows="4"
                placeholder="请输入账单地址JSON格式或文本"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 商品明细 -->
        <h3 style="margin-top: 30px;">
          商品明细
          <el-button type="primary" size="mini" @click="addOrderItem" style="margin-left: 20px;">添加商品</el-button>
        </h3>
        <el-table :data="form.orderItems" border style="width: 100%">
          <el-table-column label="序号" type="index" width="50" align="center" />
          <el-table-column label="商品SKU" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productSku" placeholder="请输入SKU" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="商品名称" min-width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productName" placeholder="请输入商品名称" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="商品英文名称" min-width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productNameEn" placeholder="请输入商品英文名称" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="规格" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.variantTitle" placeholder="请输入规格" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="数量" width="80">
            <template slot-scope="scope">
              <el-input v-model="scope.row.quantity" placeholder="数量" size="mini" type="number" @input="calculateTotal(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column label="单价" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.unitPrice" placeholder="单价" size="mini" type="number" @input="calculateTotal(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column label="小计" width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.totalPrice || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" @click="removeOrderItem(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 备注信息 -->
        <h3 style="margin-top: 30px;">备注信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单备注" prop="notes">
              <el-input
                v-model="form.notes"
                type="textarea"
                :rows="3"
                placeholder="请输入订单备注"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="系统备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入系统备注"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 操作按钮 -->
        <div style="text-align: center; margin-top: 30px;">
          <el-button type="primary" @click="submitForm">{{ isEdit ? '更新' : '保存' }}</el-button>
          <el-button @click="goBack">取消</el-button>
        </div>
      </el-card>
    </el-form>
  </div>
</template>

<script>
import { getOrder, addOrder, updateOrder } from "@/api/fiscale/order";

export default {
  name: "OrderForm",
  dicts: ['fiscale_platform_type', 'fiscale_order_status', 'fiscale_customs_status', 'fiscale_payment_status'],
  data() {
    return {
      form: {
        orderItems: []
      },
      rules: {
        orderNo: [
          { required: true, message: "订单号不能为空", trigger: "blur" }
        ],
        platformType: [
          { required: true, message: "平台类型不能为空", trigger: "change" }
        ],
        orderStatus: [
          { required: true, message: "订单状态不能为空", trigger: "change" }
        ],
        customsStatus: [
          { required: true, message: "报关状态不能为空", trigger: "change" }
        ],
        customerName: [
          { required: true, message: "客户姓名不能为空", trigger: "blur" }
        ],
        customerEmail: [
          { required: true, message: "客户邮箱不能为空", trigger: "blur" },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        totalAmount: [
          { required: true, message: "订单金额不能为空", trigger: "blur" }
        ],
        currency: [
          { required: true, message: "货币类型不能为空", trigger: "change" }
        ]
      },
      isEdit: false
    };
  },
  created() {
    this.initForm();
  },
  methods: {
    initForm() {
      const orderId = this.$route.params && this.$route.params.orderId;
      if (orderId) {
        this.isEdit = true;
        this.getOrderDetail(orderId);
      } else {
        this.isEdit = false;
        this.resetForm();
      }
    },
    getOrderDetail(orderId) {
      getOrder(orderId).then(response => {
        this.form = response.data;
        if (!this.form.orderItems) {
          this.form.orderItems = [];
        }
      });
    },
    resetForm() {
      this.form = {
        orderNo: '',
        platformOrderNo: '',
        platformType: 'manual',
        orderStatus: 'pending',
        customsStatus: 'not_declared',
        orderDate: '',
        customerName: '',
        customerEmail: '',
        customerPhone: '',
        totalAmount: 0,
        currency: 'USD',
        paymentStatus: 'pending',
        paymentMethod: '',
        shippingMethod: '',
        trackingNumber: '',
        shippingAddress: '',
        billingAddress: '',
        notes: '',
        remark: '',
        orderItems: []
      };
    },
    addOrderItem() {
      this.form.orderItems.push({
        productSku: '',
        productName: '',
        productNameEn: '',
        variantTitle: '',
        quantity: 1,
        unitPrice: 0,
        totalPrice: 0,
        weight: 0,
        hsCode: '',
        customsValue: 0,
        originCountry: 'CN'
      });
    },
    removeOrderItem(index) {
      this.form.orderItems.splice(index, 1);
      this.calculateOrderTotal();
    },
    calculateTotal(row) {
      const quantity = parseFloat(row.quantity) || 0;
      const unitPrice = parseFloat(row.unitPrice) || 0;
      row.totalPrice = (quantity * unitPrice).toFixed(2);
      this.calculateOrderTotal();
    },
    calculateOrderTotal() {
      let total = 0;
      this.form.orderItems.forEach(item => {
        total += parseFloat(item.totalPrice) || 0;
      });
      this.form.totalAmount = total.toFixed(2);
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.isEdit) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.goBack();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.goBack();
            });
          }
        }
      });
    },
    goBack() {
      this.$router.push('/fiscale/order-management/order-list');
    }
  }
};
</script>

<style scoped>
h3 {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
  padding-bottom: 10px;
  margin-bottom: 20px;
}
</style>